package com.kaigejava.webmaginc.csdn;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;

import java.util.List;

/**
 * @author kaigejava
 * csdn blog中java分类
 */
public class CsdnJavaBlog  implements PageProcessor {
    String nextPage = "https://blog.csdn.net/api/articles?type=more&category=java&shown_offset=0";
    String pageListArticUl = "//*[@id=\"feedlist_id\"]/";

    public void process(Page page) {
        //List<String> list= page.getHtml().xpath("//div[@class='article-list']/div/@data-articleid").all();
        List<String> list= page.getHtml().xpath(pageListArticUl).all();
        String  idXpath ="//*[@id=\"feedlist_id\"]/li[";
        String idXpathEnd =  "]/@data-id";
        String authXpath = "//*[@id=\"feedlist_id\"]/li[";
        String authXpathEnd = "]/div/dl/dd/a/@href";
        //提取列表页中的文章UL
        if(!list.isEmpty()) {   //存在是列表页
            for (int i = 0;i<list.size();i++) {
                String string = list.get(i);
                String id = page.getHtml().xpath(idXpath+(i+1)+idXpathEnd).toString();
                String authUrl =  page.getHtml().xpath(authXpath+(i+1)+authXpathEnd).toString();
                if(StringUtils.isNotBlank(authUrl)){
                    String articleUrl= authUrl+"/article/details/"+id;
                    page.addTargetRequest(articleUrl);
                }
            }
            //查询下一页的
            //因为下一页返回的是JSON数据 所以，需要对JSON进行解析
          //  List<String> nextInfoUrl = getNext(page ,nextPage);
        }else{  //不存在就是详情页
            this.saveCsdnArticInfo(page);
        }

    }

    private List<String> getNext(Page page, String nextPage) {
        List<String> urlList = Lists.newArrayList();
        System.out.println(page.getJson());
        String jsonStr = page.getJson().toString();
        JSONObject jsonObject =JSONObject.parseObject(jsonStr);
        boolean status = jsonObject.getBoolean("status");
        if(status){
            //获取数据集合
            JSONArray jsonArray =jsonObject.getJSONArray("articles");
            int size = jsonArray.size();
            for(int i = 0;i<size;i++){
                Object obj = jsonArray.get(i);
                JSONObject liInfo = jsonArray.getJSONObject(i);
                String url = liInfo.getString("url");
                System.out.println("url:"+url);
                urlList.add(url);
            }
        }
        return urlList;
    }


    /**
     * 保存CSDN文章
     * @param page
     */
    private void saveCsdnArticInfo(Page page) {
        //解析详情页
        String titleCss = "div.article-title-box h1";
        String articleTypeCss = "div.article-bar-top span";
        String nickNameCss = "div.article-bar-top a";
        String timeCss ="div.article-bar-top span.time";
        String readCountCss = "div.article-bar-top span.read-count";
        String contentXpath = "//*[@id=\"content_views\"]";

        Html html = page.getHtml();
        String tile = html.css(titleCss,"text").toString();
        String articleTypeStr = html.css(articleTypeCss,"text").toString();
        String nickName = html.css(nickNameCss,"text").toString();
        String time = html.css(timeCss,"text").toString().replace("最后发布于","");
        String readCount = html.css(readCountCss,"text").toString().replace("阅读数 ","");

        String content =html.xpath(contentXpath).toString();
        System.out.println("tile:"+tile+"-readCount："+readCount);
    }

    public Site getSite() {
        return Site.me().setSleepTime(100).setRetryTimes(3);
    }

    public static void main(String[] args) {
        Spider spider = Spider.create(new CsdnJavaBlog()).addUrl("https://blog.csdn.net/nav/java");
        spider.addRequest().run();
    }
}
